﻿using System.Diagnostics;
using YiJingFramework.Core;
using YiJingFramework.Painting.Deriving.Extensions;
using YiJingFramework.References.Zhouyi;
using YiJingFramework.References.Zhouyi.Zhuan;

namespace PBIW.Operating
{
    public sealed class TextProvider
    {
        public Zhouyi Zhouyi { get; }
        public XiangZhuan Xiangzhuan { get; }
        public Tuanzhuan Tuanzhuan { get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="zhouyiTranslation"></param>
        /// <param name="xiangTranslation"></param>
        /// <param name="tuanTranslation"></param>
        /// <exception cref="YiJingFramework.References.Zhouyi.Exceptions.CannotReadTranslationException"></exception>
        public TextProvider(string zhouyiTranslation, string xiangTranslation, string tuanTranslation)
        {
            this.Zhouyi = new Zhouyi(zhouyiTranslation);
            this.Xiangzhuan = new XiangZhuan(xiangTranslation);
            this.Tuanzhuan = new Tuanzhuan(tuanTranslation);
        }

        public string GetName(Painting hexagram)
        {
            Debug.Assert(hexagram.Count is 6);
            var zhouyiHexagram = this.Zhouyi.GetHexagram(hexagram);
            return zhouyiHexagram.Name;
        }
        public (string upper, string lower) GetUpperAndLowerNames(Painting hexagram)
        {
            Debug.Assert(hexagram.Count is 6);
            var zhouyiHexagram = this.Zhouyi.GetHexagram(hexagram);
            var upper = zhouyiHexagram.UpperTrigram;
            var lower = zhouyiHexagram.LowerTrigram;
            return (upper.Name, lower.Name);
        }

        public IEnumerable<(string jingText, string xiangText)> GetLineTexts(
            PlumBlossomHexagrams hexagrams)
        {
            var differences = hexagrams.Original.GetDifferentLinesBetween(hexagrams.Changed);

            var zhouyiHexagram = this.Zhouyi.GetHexagram(hexagrams.Original);
            foreach (var difference in differences)
            {
                var zhouyiLine = zhouyiHexagram.GetLine(difference + 1);
                yield return (zhouyiLine.LineText, this.Xiangzhuan[zhouyiLine]);
            }
        }
    }
}
